package com._520it.wms.service.impl;

import com._520it.wms.domain.Permission;
import com._520it.wms.mapper.PermissionMapper;
import com._520it.wms.query.PageResult;
import com._520it.wms.query.QueryObject;
import com._520it.wms.service.IPermissionService;
import com._520it.wms.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * Created by HASEE on 2017/11/14.
 */
@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;

    @Override
    public void save(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }


    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int totalCount = permissionMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult(qo.getCurrentPage(), qo.getPageSize());
        }
        //查询结果集
        List<Permission> list = permissionMapper.queryForList(qo);
        return new PageResult(qo.getCurrentPage(), qo.getPageSize(), list, totalCount);
    }

    @Override
    public void reload() {
        //如果数据库中存在对应的记录,不需要保存,通过expression来判断
        List<String> expressions = permissionMapper.queryExpressions();
        //1.遍历到所有的Controller的bean对象
        Map<String, Object> controllerMap = ctx.getBeansWithAnnotation(Controller.class);
        //2.获取到Controller中所有的方法
        for (Object obj : controllerMap.values()) {
            Method[] methods = obj.getClass().getDeclaredMethods();
            //3.判断方法是否需要权限控制@RequiredPermission
            for (Method method : methods) {
                RequiredPermission rp = method.getAnnotation(RequiredPermission.class);
                if (rp != null) {//有注解
                    //4.开始进行权限的插入操作,如果有注解,则创建一个Permission对象,将name,expression保存到数据库中
                    String expression = obj.getClass().getName() + ":" + method.getName();
                    if (!expressions.contains(expression)) {
                        Permission permission = new Permission();
                        permission.setName(rp.value());
                        permission.setExpression(expression);
                        permissionMapper.insert(permission);
                    }
                }
            }
        }
    }

    @Override
    public List<String> queryByEmpId(Long empId) {

        return permissionMapper.queryByEmpId(empId);

    }

}
